<template>
  <div class="app-container">
    <el-row class="searchArea">
      <el-form ref="formRef" :model="bodyData" :rules="rules" label-width="108px">
        <el-col :span="8">
          <el-form-item label="任务编号" prop="id">
            <el-input v-model="bodyData.id" placeholder="请输入任务编号" />
          </el-form-item>
          <el-form-item label="车牌号码" prop="licensePlate">
            <el-input v-model="bodyData.licensePlate" placeholder="请输入车牌号码" />
          </el-form-item>
          <el-form-item class="searchBtn">
            <el-button type="danger" @click="search">搜索</el-button>
            <el-button type="default" @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="任务分配状态" prop="assignedStatus">
            <el-select v-model="bodyData.assignedStatus" placeholder="请选择分配状态" prop="id" style="width: 100%">
              <el-option
                v-for="item in undistributedOptions"
                :key="item.id"
                style="width: 100%"
                :label="item.name"
                :value="item.id"
              >{{ item.name }}</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="起始地机构" class="commonSelect" prop="startAgencyId">
            <el-select
              ref="startSelect"
              v-model="bodyData.startAgencyId"
              placeholder="请选择起始地机构"
              style="width: 100%"
              class="startAgency"
              @focus="handleFocusE"
            >
              <template #prefix>
                <i
                  v-show="bodyData.startAgencyId"
                  class="el-icon-circle-close"
                  @click.stop="handlerI"
                />
              </template>
              <el-option style="padding: 0" :value="bodyData.startAgencyId" :label="startAgencyVal">
                <el-tree
                  v-show="treeShow"
                  :data="treeData"
                  node-key="id"
                  :props="defaultProps"
                  @node-click="handleCheckChange"
                />
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="满载状态" prop="loadingStatus">
            <el-select v-model="bodyData.loadingStatus" placeholder="请选择满载状态" style="width: 100%">
              <el-option
                v-for="item in fullState"
                :key="item.id"
                style="width: 100%"
                :label="item.name"
                :value="item.id"
              >{{ item.name }}</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目的地机构" prop="endAgencyId">
            <el-select
              ref="startSelect2"
              v-model="bodyData.endAgencyId"
              placeholder="请选择目的地机构"
              style="width: 100%"
              class="startAgency"
              @focus="handleFocusE2"
            >
              <template #prefix>
                <i
                  v-show="bodyData.endAgencyId"
                  class="el-icon-circle-close"
                  @click.stop="handlerI2"
                />
              </template>
              <el-option style="padding: 0" :value="bodyData.endAgencyId" :label="endAgencyVal">
                <el-tree
                  v-show="treeShow2"
                  :data="treeData"
                  node-key="id"
                  :props="defaultProps"
                  @node-click="handleCheckChange2"
                />
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>

    <!-- 筛选 -->
    <el-row class="choose">
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane :label="`全部（${totalNum}）`" name="first" />
        <el-tab-pane :label="`待提货（${totalTitData[1]}）`" name="second" />
        <el-tab-pane :label="`进行中（${totalTitData[2]}）`" name="third" />
        <el-tab-pane :label="`已完成（${totalTitData[4]}）`" name="fourth" />
        <el-tab-pane :label="`已取消（${totalTitData[5]}）`" name="fivth" />
      </el-tabs>
    </el-row>

    <!-- 表格数据 -->
    <div class="table">
      <el-table
        v-show="showTable"
        v-loading="loading"
        :data="tableData"
        element-loading-text="拼命加载中"
        border
        style="width: 100%"
      >
        <el-table-column
          align="center"
          width="80px"
          type="index"
          label="序号"
          :index="indexFn"
        />
        <el-table-column
          align="center"
          width="180px"
          prop="id"
          label="任务编号"
        />
        <el-table-column
          align="center"
          width="110px"
          prop="truck.licensePlate"
          label="车牌号码"
        />
        <el-table-column
          width="110px"
          align="center"
          prop="startAgency.name"
          label="起始地"
        />
        <el-table-column
          align="center"
          prop="endAgency.name"
          width="110px"
          label="目的地"
        />
        <el-table-column
          align="center"
          prop="status"
          width="80px"
          label="任务状态"
        >
          <template #default="{row}">
            {{ row.status === 1 ? '待提货' : row.status === 2 ? '进行中' : row.status === 3 ? '待确认' : row.status === 4 ? '已完成' : '已取消' }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="loadingStatus"
          label="车辆装载状态"
          width="120px"
        >
          <template #default="{row}">
            {{ row.loadingStatus === 1 ? '半载' : row.loadingStatus === 2 ? '满载' : row.loadingStatus === 3 ? '空载' : '' }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="assignedStatus"
          width="110px"
          label="任务分配状态"
          class="taskClass"
        >
          <template #default="{row}">
            {{ row.assignedStatus === 2 ? '已分配' : row.assignedStatus === 3 ? '待人工分配' : '' }}
          </template>
        </el-table-column>

        <el-table-column
          width="170px"
          align="center"
          prop="planDepartureTime"
          label="计划发车时间"
        >
          <template #default="{row}">
            {{ row.planDepartureTime ? row.planDepartureTime : '无' }}
          </template>
        </el-table-column>
        <el-table-column
          width="200px"
          align="center"
          prop="actualDepartureTime"
          label="实际发车时间"
        >
          <template #default="{row}">
            {{ row.actualDepartureTime ? row.actualDepartureTime : '无' }}
          </template>
        </el-table-column>
        <el-table-column
          width="200px"
          align="center"
          prop="updated"
          label="更新时间"
        />
        <el-table-column
          class="opera"
          align="center"
          label="操作"
          fixed="right"
          width="160px"
        >
          <template #default="{row}">
            <el-button type="text" class="elBtn">查看</el-button>
            <el-button type="text" @click="handlerCancel(row.id)">取消</el-button>
            <el-button type="text" class="elBtn" @click="handleSet(row)">手动调整</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-show="showTable"
        style="margin-top: 20px"
        :current-page="bodyData.page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="bodyData.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <el-empty v-show="!showTable" description="暂无数据" />
    </div>
    <Footer />
    <ManaulSet
      v-if="showDialog"
      :dialog-data="dialogData"
      :show-dialog.sync="showDialog"
      class="newDialog"
    />
  </div>
</template>

<script>
import { transportData, transportDataCount, cancelTask } from '@/api/transport'
import { netWorkPoint } from '@/api/network'
import Footer from '@/components/Footer.vue'
import ManaulSet from '../components/ManaulSet.vue'

export default {
  components: {
    Footer,
    ManaulSet
  },
  data() {
    return {
      showDialog: false,
      loading: true,
      activeName: 'first',
      tableData: [],
      totalTitData: [],
      showTable: true,
      total: 0,
      allData: 0,
      bodyData: {
        assignedStatus: '',
        endAgencyId: null,
        id: '',
        page: 1,
        pageSize: 5,
        licensePlate: '',
        loadingStatus: '',
        planArrivalTime: '',
        startAgencyId: null,
        status: null,
        truckId: null
      },
      undistributedOptions: [{ id: 1, name: '未分配' }, { id: 2, name: '已分配' }, { id: 3, name: '待人工分配' }],
      fullState: [{ id: 1, name: '半载' }, { id: 2, name: '满载' }, { id: 3, name: '空载' }],
      endAgencyVal: null,
      startAgencyVal: null,
      treeData: [],
      defaultProps: {
        label: 'name'
      },
      treeShow: false,
      treeShow2: false,
      dialogData: {},
      rules: {
        id: [
          { pattern: /^\d+$/, message: '请填写正确的数字', trigger: ['blur', 'change'] }
        ],
        licensePlate: [
          { pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/i, message: '请填入正确的车牌', trigger: ['blur', 'change'] }
        ],
        endAgencyId: [
          {
            validator: (rule, value, callback) => {
              if (value) {
                if (this.bodyData.startAgencyId === value) {
                  callback(new Error('目的地机构不能与起始地机构同名'))
                } else {
                  callback()
                }
              }
            }
          }
        ],
        startAgencyId: [
          {
            validator: (rule, value, callback) => {
              if (value) {
                if (this.bodyData.endAgencyId === value) {
                  callback(new Error('起始地机构不能与目的地机构同名'))
                } else {
                  callback()
                }
              }
            }
          }
        ]
      }
    }
  },
  computed: {
    totalNum() {
      return Object.values(this.totalTitData).reduce((sum, item) => sum + Number(item), 0)
    }
  },
  created() {
    this.getTransportData()
    this.getTransportData2()

    // 初始化获取树形网点
    this.getNetWorkPoints()
  },
  methods: {
    // 手动调整
    handleSet(val) {
      this.dialogData = val
      this.showDialog = true
    },
    // 点击取消
    handlerCancel(val) {
      this.$confirm('确定取消此运输任务吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await cancelTask(String(val))
        this.getTransportData()
        this.$message({
          type: 'success',
          message: '取消成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        })
      })
    },
    // 点击搜索
    async search() {
      this.loading = true
      await this.getTransportData(this.bodyData)
    },
    // 重置表单
    resetForm() {
      this.loading = true
      this.$refs.formRef.resetFields()
      this.getTransportData()
    },
    // 点击起始地下拉框差号
    handlerI() {
      this.startAgencyVal = ''
      this.bodyData.startAgencyId = ''
      this.$refs.startSelect.blur()
    },
    // 起始地下拉框聚焦后树形数据显示
    handleFocusE() {
      this.treeShow = true
    },
    // 选中起始地下拉框树形数据后
    handleCheckChange(val) {
      this.bodyData.startAgencyId = val.id
      this.startAgencyVal = val.name
      this.$refs.startSelect.blur()
      this.treeShow = false
    },
    // 点击目的地机构下拉框差号
    handlerI2() {
      this.endAgencyVal = ''
      this.bodyData.endAgencyId = ''
      this.$refs.startSelect2.blur()
    },
    // 目的地机构下拉框聚焦后树形数据显示
    handleFocusE2() {
      this.treeShow2 = true
    },
    // 选中目的地机构下拉框树形数据后
    handleCheckChange2(val) {
      this.bodyData.endAgencyId = val.id
      this.endAgencyVal = val.name
      this.$refs.startSelect2.blur()
      this.treeShow2 = false
    },
    // 获取树形网点
    async getNetWorkPoints() {
      const res = await netWorkPoint()
      this.treeData = JSON.parse(res)
    },
    // 改变分页大小
    handleSizeChange(val) {
      this.loading = true
      this.bodyData.page = 1
      this.bodyData.pageSize = val
      this.getTransportData()
    },

    // 改变页码
    handleCurrentChange(val) {
      this.loading = true
      this.bodyData.page = val
      this.getTransportData()
    },
    // 获取切换数据
    async getTransportData2() {
      this.totalTitData = await transportDataCount()
    },
    // 获取表格数据
    async getTransportData() {
      const res = await transportData(this.bodyData)
      this.tableData = res.items
      res.items?.length ? this.showTable = true : this.showTable = false
      this.loading = false
      this.total = Number(res.counts)
    },
    // 点击tab切换数据
    handleClick(val) {
      const status = val.index
      this.loading = true
      this.bodyData.page = 1
      if (status === '0') {
        this.bodyData.status = ''
      } else if (status === '1') {
        this.bodyData.status = '1'
      } else if (status === '2') {
        this.bodyData.status = '2'
      } else if (status === '3') {
        this.bodyData.status = '4'
      } else if (status === '4') {
        this.bodyData.status = '5'
      }
      this.getTransportData()
    },
    // 表格序号
    indexFn(index) {
      return index + 1
    }
  }
}
</script>

<style scoped lang="scss">
  .table {
    margin-top: 20px;
    padding: 20px;
    background-color: #fff;
    text-align: center;
  }
  .searchArea {
    background-color: #fff;
    padding: 20px;
    box-sizing: border-box;
    .el-col-8 {
      width: 31%;
    }
  }
  .choose {
    margin-top: 14px;
    background-color: #fff;
    ::v-deep .el-tabs__header {
      margin-bottom: 0;
    }
  }
  .elBtn {
    color: #7bbcff
  }
  .el-select-dropdown__item {
    height: auto;
  }
  .startAgency {
    position: relative;
    .el-icon-circle-close {
      position: absolute;
      right: -356px;
      top: 14px;
      cursor: pointer;
      &:hover {
        color:red
      }
    }
  }
  .newDialog {
    ::v-deep .el-dialog {
      width: 40%
    }
  }
  .startAgency {
    ::v-deep .el-input__inner {
      padding-left: 14px;
    }
  }

</style>
